<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

</body>
<script>
    //把字符串前面补0，使长度为len
    function addZero(str, len) {
        let n = len - str.length;
        let c = '';
        for (let i = 0; i < n; i++) {
            c += '0';
        }
        c += str;
        return c
    }
    var addBinary = function (a, b) {
        const len = (a.length > b.length ? a.length : b.length);
        a = addZero(a, len); //调用函数，让a,b字符串长度相等
        b = addZero(b, len);
        let c = [];
        for (let i = 1; i <= len; i++) {
            //直接把a，b进行相加，赋值给c数组
            c[len - i] = (a[a.length - i] - 0) + (b[b.length - i] - 0);
        }
        //遍历c
        for (let i = c.length - 1; i >= 0; i--) {
            if (c[i] >= 2) {
                c[i] %= 2; //取余2转成二进制
                if ((i) == 0) { //如果是第一位则在前面再加一个元素
                    c.unshift(1);
                } else {
                    c[i - 1] += 1; //使其前一位加一
                }

            }
        }
        return c.join(''); //将数组转成字符串
    };
    a = '1111';
    b = '1111';
    console.log(addBinary(a, b));
</script>

</html>